package cn.web.tunnelrobot.util;

import cn.web.tunnelrobot.dto.FileDTO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.VideoAttributes;
/**
 * 文件上传+文件压缩
 */
public class UploadImage {
	public static final String imagePath="/uploadfiles/"; //定义上传文件的存放位置
//	public static final String imageDir="C://TunnelRobotFile//"; //定义上传文件的存放位置---本机
    public static final String imageDir="C://SecondTunnelRobotFile//"; //定义上传文件的存放位置---本机 为避免与已经部署上线的文件混淆
	/*public static final String imagePath="/upload/"; //定义上传文件的存放位置
	public static final String imageDir="/Users/gaobaoqu/Documents/upload1/"; //定义上传文件的存放位置---本机*/
//    public static final String imageDir="/www/TunnelRobotFile/"; //定义上传文件的存放位置---服务器

	public static FileDTO upLoadVoiceFile(MultipartFile file) {
		String filename = file.getOriginalFilename();//原始文件名
		String suffix = filename.substring(filename.lastIndexOf('.'));
		//fileName=+fileF;//新的文件名
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(new Date());
		String imageName = "语音对讲-"+dateString+"-"+new Random().nextInt(10000) + suffix;
		String url = imagePath + imageName;
		String absolutePath = imageDir + imageName;
		File dest = new File(absolutePath);
		//判断目录是否存在
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		try {
			file.transferTo(dest);
		} catch (Exception e) {
			System.out.println("保存图片异常");
			e.printStackTrace();
		}
		FileDTO fileDTO = new FileDTO();
		fileDTO.setFiFilePath(url);
		fileDTO.setFiOldName(filename);
		System.out.println("imageUrl:"+url);
		return fileDTO;
	}
	public static FileDTO upLoadFile1(MultipartFile file) {
		String filename = file.getOriginalFilename();//原始文件名
		String suffix = filename.substring(filename.lastIndexOf('.'));
		//fileName=+fileF;//新的文件名
		String imageName = new Date().getTime()+new Random().nextInt(10000) + suffix;
		String url = imagePath + imageName;
		String absolutePath = imageDir +imageName;
		File dest = new File(absolutePath);
		//判断目录是否存在
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		try {
			file.transferTo(dest);
		} catch (Exception e) {
			System.out.println("保存图片异常");
			e.printStackTrace();
		}
		FileDTO fileDTO = new FileDTO();
		fileDTO.setFiFilePath(url);
		fileDTO.setFiOldName(filename);
		System.out.println("imageUrl:"+url);
		return fileDTO;
	}
	public static String upLoadFile(MultipartFile file) {
			String filename = file.getOriginalFilename();//原始文件名
			String suffix = filename.substring(filename.lastIndexOf('.'));
			//fileName=+fileF;//新的文件名
			String imageName = new Date().getTime()+new Random().nextInt(10000) + suffix;
			String url = imagePath + imageName;
			String absolutePath = imageDir +imageName;
			File dest = new File(absolutePath);
			//判断目录是否存在
			if (!dest.getParentFile().exists())
				dest.getParentFile().mkdirs();
			try {
				file.transferTo(dest);
//				File file1 = multipartFileToFile(file);
//				zipImageFile(file1,new File(absolutePath),864,1200,0.7f);
//				file1.delete();
			} catch (Exception e) {
				System.out.println("保存图片异常");
				e.printStackTrace();
			}
		System.out.println("imageUrl:"+url);
		return url;
	}
	/**
	 * 根据设置的宽高等比例压缩图片文件<br> 先保存原文件，再压缩、上传
	 * @param oldFile 要进行压缩的文件
	 * @param newFile 新文件
	 * @param width 宽度 //设置宽度时（高度传入0，等比例缩放）
	 * @param height 高度 //设置高度时（宽度传入0，等比例缩放）
	 * @param quality 质量
	 * @return 返回压缩后的文件的全路径
	 */
	public static String zipImageFile(File oldFile,File newFile, int width, int height,float quality) {
		if (oldFile == null) {
			return null;
		}
		try {
			/** 对服务器上的临时文件进行处理 */
			Image srcFile = ImageIO.read(oldFile);
			int w = srcFile.getWidth(null);
			int h = srcFile.getHeight(null);
			double bili;
			if(width>0){
				bili=width/(double)w;
				height = (int) (h*bili);
			}else{
				if(height>0){
					bili=height/(double)h;
					width = (int) (w*bili);
				}
			}
			String srcImgPath = newFile.getAbsoluteFile().toString();
			System.out.println(srcImgPath);
			String subfix = "jpg";
			subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1,srcImgPath.length());
			BufferedImage buffImg = null;
			if(subfix.equals("png")){
				buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
			}else{
				buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			}
			Graphics2D graphics = buffImg.createGraphics();
			graphics.setBackground(new Color(255,255,255));
			graphics.setColor(new Color(255,255,255));
			graphics.fillRect(0, 0, width, height);
			graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
			ImageIO.write(buffImg, subfix, new File(srcImgPath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return newFile.getAbsolutePath();
	}

	public static File multipartFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if (file.equals("") || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}

	//获取流文件
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
     *创建FileItem   file转MultipartFile
     */
	public static MultipartFile updateFileToMultipartFile(File file) {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
		FileItem item = factory.createItem(null, "text/plain", true, file.getName());
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		try {
			FileInputStream fis = new FileInputStream(file);
			OutputStream os = item.getOutputStream();
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		MultipartFile mfile = new CommonsMultipartFile(item);
		return mfile;
	}
	/**
	 * 链接url下载图片
	 * 文件保存路径、文件路径
	 */
	public static void downloadPicture(String urlList,String path) {
		URL url = null;
		try {
			url = new URL(urlList);
			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 链接url下载视频
	 * 文件保存路径、文件路径
	 */
	public static boolean downloadVideo(String httpUrl, String saveFile) {
		// 1.下载网络文件
		int byteRead;
		URL url;
		try {
			url = new URL(httpUrl);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return false;
		}
		try {
			//2.获取链接
			URLConnection conn = url.openConnection();
			//3.输入流
			InputStream inStream = conn.getInputStream();
			//3.写入文件
			FileOutputStream fs = new FileOutputStream(saveFile);
			byte[] buffer = new byte[1024];
			while ((byteRead = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteRead);
			}
			inStream.close();
			fs.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 上传word文件
	 */
	public static String upLoadFiles(MultipartFile file) {
		String fileUrl = "";
		String filename = file.getOriginalFilename();//原始文件名
		String suffix = filename.substring(filename.lastIndexOf('.'));
		//fileName=+fileF;//新的文件名
		String imageName = new Date().getTime()+new Random().nextInt(10000) + suffix;
		String url = imagePath + imageName;
		String absolutePath = imageDir +imageName;
		File dest = new File(absolutePath);
		//判断目录是否存在
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		try {
			file.transferTo(dest);
		} catch (IOException e) {
			System.out.println("保存文件异常");
			e.printStackTrace();
		}
		if(fileUrl.equals("")){
			fileUrl = url;
		}else{
			fileUrl = fileUrl + "," + url;
		}
		System.out.println("file:"+fileUrl);
		return fileUrl;
	}


	/**
	 * 上传视频文件和转码
	 */
	public static String upLoadVideoFile(MultipartFile file) {
		String fileUrl = "";
		String filename = file.getOriginalFilename();//原始文件名
		String suffix = filename.substring(filename.lastIndexOf('.'));
		//fileName=+fileF;//新的文件名
		String imageName = new Date().getTime()+new Random().nextInt(10000) + suffix;
		String url = imagePath + imageName;
		String absolutePath = imageDir +imageName;
		File dest = new File(absolutePath);
		//判断目录是否存在
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		try {
			file.transferTo(dest);
		} catch (IOException e) {
			System.out.println("保存文件异常");
			e.printStackTrace();
		}
		if(fileUrl.equals("")){
			fileUrl = url;
		}else{
			fileUrl = fileUrl + "," + url;
		}
		System.out.println("视频file:"+fileUrl);
		System.out.println("视频file:"+fileUrl.substring(13));
		System.out.println("视频file:"+imageDir+fileUrl.substring(13));
		File source = new File(imageDir + fileUrl.substring(13));
		String imageName1 = new Date().getTime()+new Random().nextInt(10000) + suffix;
		File target = new File(imageDir + imageName1);
		String url1 = imagePath + imageName1;
		if(StringUtils.isNotEmpty(imageName1)){
			fileUrl = url1;
		}
		System.out.println("视频file2:"+fileUrl);
		System.out.println("视频file2:"+fileUrl.substring(13));
		System.out.println("视频file2:"+imageDir+fileUrl.substring(13));
		try {
			System.out.println("begin");
			AudioAttributes audio= new AudioAttributes();
			audio.setCodec("AAC");
			audio.setBitRate(new Integer(56000));
			audio.setChannels(new Integer(1));
			audio.setSamplingRate(new Integer(22050));
			VideoAttributes video=new VideoAttributes();
			video.setCodec(VideoAttributes.DIRECT_STREAM_COPY);
			video.setBitRate(new Integer(800000));
			video.setFrameRate(new Integer(15));
			EncodingAttributes attr=new EncodingAttributes();
			attr.setFormat("mp4");
			attr.setAudioAttributes(audio);
			attr.setVideoAttributes(video);
			Encoder encoder=new Encoder();
			encoder.encode(source, target, attr);
			System.out.println("end");
			//source.delete();
			System.out.println("---------------------文件创建日期");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileUrl;
	}
}
